import http from '@ohos.net.http';

class NetworkTool {

  static buildUrlByParams(url: string, params: { [key: string]: any }): string {
    const queryParams = Object.entries(params)
      .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
      .join('&');
    return queryParams ? `${url}?${queryParams}` : url;
  }

  static shared = http.createHttp();

  static GET = async <T>(url: string, params: any): Promise<{ data: T } | null> => {
    // 重新构建URL
    const newUrl = NetworkTool.buildUrlByParams(url, params);

    return new Promise((resolve, reject) => {
      NetworkTool.shared.request(
        newUrl,
        {
          method: http.RequestMethod.GET,
          header: {
            "Content-Type": "application/json"
          }
        },
        (err, data) => {
          if (err) {
            reject(err);
            return;
          }

          try {
            console.log("%s请求结果:%s",newUrl,data.result)
            const result: { data: T } = JSON.parse(data.result as string);
            resolve(result);
          } catch (parseError) {
            reject(parseError);
          }
        }
      );
    });
  };

  // POST、DELETE、PUT ...
}

export default NetworkTool;
